<template>
  <div class="setting-container">
    <page-Tole :showBefore="true">
      <span slot="before">共{{query.total}}条记录</span>
      <el-button slot="after" type="danger" sizi="mini" @click="downloadExcel">导出Excel</el-button>
      <el-button slot="after" type="primary" sizi="mini" @click="$router.push('/import')">导入Excel</el-button>
      <el-button icon="el-icon-plus" slot="after" type="primary" @click="dialogFormVisible = true"
        sizi="mini">新增员工</el-button>
    </page-Tole>
    <el-card>
      <el-table v-loading="loading" ref="singleTable" :data="tableData" border>
        <el-table-column type="index" label="序号" sortable />
        <el-table-column prop="username" label="姓名" sortable />
        <el-table-column prop="staffPhoto" label="头像">
          <template v-slot="{row}">
            <img @click="showQrCode(row.staffPhoto)" v-imagerror="defaultimg" :src="row.staffPhoto"
              style="border-radius: 50%; width: 100px; height: 100px; cursor:pointer; padding:10px" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="workNumber" label="工号" sortable :sort-method="workNumberSortFn" />
        <el-table-column prop="formOfEmployment" :formatter="formatEmployment" label="聘用形式" sortable />
        <el-table-column prop="departmentName" label="部门" sortable />
        <el-table-column prop="timeOfEntry" label="入职时间" sortable>
          <template v-slot="{row}">
            <span>{{ formatTime(row.timeOfEntry) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="enableState" label="账户状态" sortable>
          <template v-slot="{row}">
            <el-switch :value="row.enableState ==1 ?true :false" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
          </template>

        </el-table-column>
        <el-table-column label="操作" sortable width="280">
          <template v-slot="{row}">
            <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="rouBtn(row)">角色</el-button>
            <el-button type="text" size="small" @click="deleteEmp(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="query.page" :page-size="query.size" layout="total, prev, pager, next"
          :total="query.total">
        </el-pagination>
      </el-row>
    </el-card>
    <el-dialog title="二维码" :visible.sync="showCodeDialog" @close="imgUrl=''">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <allotRouter v-if="dialogFormVisible1" ref="Roule" :userId="userId" :dialogFormVisible1.sync="dialogFormVisible1" />
    <empDialog :dialogFormVisible.sync="dialogFormVisible"></empDialog>
  </div>
</template>

<script>
  import { getEmployeesAPI, deleteEmployeeIdAPI } from '@/api'
  import EmployeeEnum from '@/api/constant/employees.js'
  import allotRouter from './allot-router'
  import { parseTime } from '@/utils'
  import empDialog from './components/empDialog.vue'
  import dayjs from 'dayjs'
  import QrCode from 'qrcode'
  export default {
    inject: ['reload'],
    data () {
      return {
        tableData: [],
        query: {
          total: 0,
          page: 1, //当前页面
          size: 10 //每页显示的数目
        },
        userId: '',
        dialogFormVisible1: false,  //修改权限弹出层
        showCodeDialog: false,  //弹出层，默认为false
        defaultimg: require('@/assets/common/head.jpg'),
        userRelations: {
          '编号': 'id',
          '密码': 'password',
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName',
          '头像地址': 'staffPhoto'
        }, //映射关系
        loading: false,
        dialogFormVisible: false,
      }
    },
    created () {
      this.getEmployees()
    },
    components: { empDialog, allotRouter },
    methods: {
      rouBtn (row) {
        // 点击角色时的事件
        this.dialogFormVisible1 = true
        this.userId = row.id
      },
      parseTime,
      // 格式化时间
      formatTime (time) {
        return dayjs(time).format('YYYY-MM-DD')
      },
      // 获取员工列表数据
      async getEmployees () {
        this.loading = true
        const { total, rows } = await getEmployeesAPI(this.query)
        this.tableData = rows
        this.query.total = total
        this.loading = false
      },
      // 删除员工
      deleteEmp (row) {
        this.$confirm('您确定进行删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(async () => {
          this.loading = true
          try {
            await deleteEmployeeIdAPI(row.id)
            this.$message.success('删除成功')
            // 删除完后重新拉取页面
            this.getEmployees()
            this.loading = false
          } catch (err) {
            console.log(err);
            this.loading = false
          }
        }).catch(() => {
          console.log(123);
        })
      },
      // 	pageSize 改变时会触发
      handleSizeChange () { },
      // currentPage 改变时会触发
      handleCurrentChange (val) {
        this.query.page = val
        this.getEmployees(this.query)
      },
      formatEmployment (row, column, cellValue, index) {
        const obj = EmployeeEnum.hireType.find(item => {
          return item.id === Number(cellValue)
        })
        return obj ? obj.value : '未知'
      },
      showQrCode (url) {
        if (url && String(url).trim()) {
          // 如果有url,显示弹层
          this.showCodeDialog = true
          this.$nextTick(() => {
            QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          })
        } else {
          this.$message.info('用户头像为空')
        }

      },
      workNumberSortFn (a, b) {
        // 打印a和b发现是表格数组里的对象
        // sort方法使用:
        // 如果return小于0, 那么 a 会被排列到 b 之前
        // 如果return等于0, 那么 a 和 b 位置不变
        // 如果return大于0, 那么 a 会被排列到 b 之后
        return parseInt(a.workNumber) - parseInt(b.workNumber)
      },
      // 导出Excel
      downloadExcel () {
        import('@/vendor/Export2Excel').then(async excel => {
          const { rows } = await getEmployeesAPI({ page: 1, size: this.query.total })
          const data = this.transData(rows)
          const multiHeader = [['编号', '', '', '姓名', '', '', '', '', '', '',]] //复杂表头
          const merges = ['A1:A2', 'B1:C1', 'D1:D2', 'E1:J1']
          // excel表示导入的模块对象
          excel.export_json_to_excel({
            header: Object.keys(this.userRelations), // 表头 必填
            data,
            filename: 'excel-list', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx', // 生成的文件类型
            multiHeader,
            merges
          })
        })
      },
      transData (rows) {
        const userKey = Object.keys(this.userRelations)
        return rows.map(item => {
          return userKey.map(key => {
            if (this.userRelations[key] === 'timeOfEntry' || this.userRelations[key] === 'correctionTime') {
              item[this.userRelations[key]] = this.formatTime(item[this.userRelations[key]])
            }
            else if (this.userRelations[key] === 'formOfEmployment') {
              let obj = EmployeeEnum.hireType.find(item1 => { return item1.id == item[this.userRelations[key]] })
              item[this.userRelations[key]] = obj ? obj.value : '未知'
            }
            return item[this.userRelations[key]]
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>